package com.yunhe.common.util;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 简易模式的本地缓存
 */
@Component
public class SimpleLocalCache {
	private Map<String, Object> valueMap = new ConcurrentHashMap<>();
	private Map<String, Long> expireTimeMap = new ConcurrentHashMap<>();

	/**
	 * 取值
	 * @param key 键
	 */
	public Object getValue(String key) {
		if (valueMap.containsKey(key)) {
			Long expireTime = expireTimeMap.get(key);
			if (System.currentTimeMillis() <= expireTime) {
				return valueMap.get(key);
			}
		}
		return null;
	}

	/**
	 * 设值
	 * @param key 键
	 * @param value 值
	 * @param liveTime 存活时间（秒）
	 */
	public void setValue(String key, Object value, int liveTime) {
		valueMap.put(key, value);
		expireTimeMap.put(key, System.currentTimeMillis() + liveTime * 1000);
	}

	/**
	 * 移除
	 * @param key 键
	 */
	public void remove(String key) {
		valueMap.remove(key);
		expireTimeMap.remove(key);
	}
}
